<template>
  <div class="container">
    <!-- 面包屑导航 -->
    <div class="topNav">
      <el-breadcrumb :separator-icon="ArrowRight">
        <el-breadcrumb-item :to="{ name: 'base' }">仓库系统</el-breadcrumb-item>
        <el-breadcrumb-item>调拨单</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <!-- 编辑/新增 调拨单操作区域 -->
    <div class="together-content">
      <!-- 调拨表单 -->
      <div>
        <el-form :inline="true" label-width="auto" style="width: 100%;">
          <!-- 单据编号 -->
          <el-form-item label="单据编号:" v-show="allotOrder.code">
            <span v-show="allotOrder.status >= 2">{{ allotOrder.code }}</span>
            <el-input v-show="allotOrder.status < 2" v-model="allotOrder.code" style="width: 150px; " readonly />
          </el-form-item>

          <!-- 单据日期 -->
          <el-form-item label="单据日期:">
            <span v-if="allotOrder.status >= 2">{{ allotOrder.createdTime }}</span>
            <el-date-picker v-else-if="allotOrder.status < 2" v-model="allotOrder.createdTime" type="date" placeholder="选择日期" size="small"
              style="width: 150px" value-format="YYYY-MM-DD" />
          </el-form-item>

          <!-- 上传附件（只读时不显示链接） -->
          <el-form-item v-show="allotOrder.status < 2">
            <el-link type="primary" style="margin-left: 20px; height: 1.2rem">
              <el-icon>
                <Link />
              </el-icon>上传附件
            </el-link>
          </el-form-item>
        </el-form>
      </div>

      <!-- 分割线 -->
      <el-divider />

      <!-- 操作按钮（只在 status < 2 时显示） -->
      <div v-show="allotOrder.status < 2" style="margin-bottom: 15px; text-align: right">
        <el-button type="primary" size="small" @click="save">保存</el-button>
        <el-button type="success" size="small" @click="saveAndSubmit">保存并提交</el-button>
        <el-button type="success" size="small" v-show="allotOrder.status == 2" @click="auditor">审核</el-button>
        <el-button type="info" size="small">反审核</el-button>
      </div>

      <!-- 调拨明细 -->
      <el-table :data="detailList" style="width: 100%" border>
        <!-- 操作列（只在可编辑时显示） -->
        <el-table-column v-if="allotOrder.status < 2" label="操作" width="80px" align="center" fixed="left">
          <template #default="scope">
            <el-button link type="success" size="small" plain @click="addDetailRow(scope.$index)">
              <el-icon>
                <Plus />
              </el-icon>
            </el-button>
            <el-button link type="danger" size="small" plain @click="removeDetailRow(scope.$index)">
              <el-icon>
                <Minus />
              </el-icon>
            </el-button>
          </template>
        </el-table-column>

        <!-- 商品 -->
        <el-table-column label="商品" width="200px" align="center">
          <template #default="scope">
            <span v-show="allotOrder.status >= 2">{{ scope.row.goodsName }}</span>
            <el-input v-show="allotOrder.status < 2" v-model="scope.row.goodsName" size="small" style="width: 95%" placeholder="选择商品"
              @click="openGoodsDialog(scope.row, scope.$index)" readonly />
          </template>
        </el-table-column>

        <!-- 商品类别 -->
        <el-table-column label="商品类别" width="180px" align="center">
          <template #default="scope">
            <span v-show="allotOrder.status >= 2">{{ scope.row.categoryName }}</span>
            <el-input v-show="allotOrder.status < 2" v-model="scope.row.categoryName" size="small" style="width: 95%" placeholder="商品类别"
              readonly />
          </template>
        </el-table-column>

        <!-- 规格 -->
        <el-table-column label="规格" width="150px" align="center">
          <template #default="scope">
            <span v-show="allotOrder.status >= 2">{{ scope.row.specification }}</span>
            <el-input v-show="allotOrder.status < 2" v-model="scope.row.specification" size="small" style="width: 95%" placeholder="规格"
              readonly />
          </template>
        </el-table-column>

        <!-- 单位 -->
        <el-table-column label="单位" width="150px" align="center">
          <template #default="scope">
            <span v-show="allotOrder.status >= 2">{{ scope.row.unitName }}</span>
            <el-select v-show="allotOrder.status < 2" v-model="scope.row.unitName" size="small" style="width: 95%"
              :disabled="!scope.row.goodsId">
            </el-select>
          </template>
        </el-table-column>

        <!-- 调出仓库 -->
        <el-table-column label="调出仓库" width="200px" align="center">
          <template #default="scope">
            <span v-show="allotOrder.status >= 2">{{ scope.row.sourceWarehouseName || '(所有)' }}</span>
            <el-input v-show="allotOrder.status < 2" v-model="scope.row.sourceWarehouseName" readonly placeholder="(所有)"
              @click="openWarehouseDialog(scope.row, 'source')" style="width: 95%" size="small" />
          </template>
        </el-table-column>

        <!-- 调入仓库 -->
        <el-table-column label="调入仓库" align="center" width="200px">
          <template #default="scope">
            <span v-show="allotOrder.status >= 2">{{ scope.row.targetWarehouseName }}</span>
            <el-input v-show="allotOrder.status < 2" v-model="scope.row.targetWarehouseName" readonly size="small" placeholder="选择仓库"
              @click="openWarehouseDialog(scope.row, 'target')" style="width: 95%" />
          </template>
        </el-table-column>

        <!-- 可用库存 -->
        <el-table-column label="可用库存(调出仓)" width="180px" align="center">
          <template #default="scope">
            <span v-show="allotOrder.status >= 2">{{ scope.row.availableStock }}</span>
            <el-input v-show="allotOrder.status < 2" v-model="scope.row.availableStock" size="small" style="width: 95%" placeholder="可用库存"
              readonly />
          </template>
        </el-table-column>

        <!-- 批次号 -->
        <el-table-column v-if="showBatch" prop="batchNo" label="批次号" width="180px" align="center">
          <template #default="scope">
            <span v-show="allotOrder.status >= 2">{{ scope.row.batchNo }}</span>
            <el-input v-show="allotOrder.status < 2" v-model="scope.row.batchNo" size="small" @click="openBatchDialog(scope.row, scope.$index)"
              style="width: 95%" />
          </template>
        </el-table-column>

        <!-- 生产日期 -->
        <el-table-column v-if="showBatch" prop="birthday" label="生产日期" width="180px" align="center">
          <template #default="scope">
            <span v-show="allotOrder.status >= 2">{{ scope.row.birthday }}</span>
            <el-input v-show="allotOrder.status < 2" v-model.number="scope.row.birthday" size="small" :disabled="scope.row.manageType == true"
              style="width: 95%" />
          </template>
        </el-table-column>

        <!-- 有效期 -->
        <el-table-column v-if="showBatch" prop="expiration" label="有效期(天)" width="150px" align="center">
          <template #default="scope">
            <span v-show="allotOrder.status >= 2">{{ scope.row.expiration }}</span>
            <el-input v-show="allotOrder.status < 2" v-model.number="scope.row.expiration" size="small" :disabled="scope.row.manageType == true"
              style="width: 95%" />
          </template>
        </el-table-column>

        <!-- 数量 -->
        <el-table-column prop="quantity" label="数量" width="150px" align="center">
          <template #default="scope">
            <span v-show="allotOrder.status >= 2">{{ scope.row.quantity }}</span>
            <el-input-number v-show="allotOrder.status < 2" v-model.number="scope.row.quantity" :step="1" size="small" style="width: 95%"
              :min="1" :max="100000000" @input="scope.row.totalPrice = scope.row.unitPrice * scope.row.quantity" />
          </template>
        </el-table-column>
      </el-table>
      <br />

      <!-- 备注 -->
      <div v-show="allotOrder.status >= 2">
        <p><strong>备注：</strong><span>{{ allotOrder.remark || '暂无备注信息' }}</span></p>
      </div>
      <el-input v-show="allotOrder.status < 2" v-model="allotOrder.remark" style="width: 100%" type="textarea" placeholder="暂无备注信息" />

      <!-- 操作日志 & 历史记录 -->
      <div style="margin-bottom: 15px; text-align: right">
        <br />
        <el-button plain @click="router.push({ name: 'allot' })">历史记录</el-button>
        <el-button plain>操作日志</el-button>
      </div>

      <!-- 弹窗（仅在可编辑时需要） -->
      <!-- ⚠️ 弹窗必须用 v-if！否则即使隐藏，也会渲染内容，影响性能和逻辑 -->
      <!-- 所以这里保留 v-if -->
      <template v-if="allotOrder.status < 2">
        <!-- 仓库搜索列表弹出对话框 -->
        <el-dialog v-model="warehouseVisible" title="仓库搜索列表" width="40%" style="height: auto;" draggable
          :show-close="true">
          <WareHouse ref="warehouseRef"
            :info="{ selection: true, no: false, name: true, code: true, status: false, op: false, outButton: true }" />
          <br /><br />
        </el-dialog>

        <!-- 商品搜索列表弹出对话框 -->
        <el-dialog v-model="goodsVisible" title="商品搜索列表" style="height: auto; width: 70%;" draggable :show-close="true">
          <FreeGoodsSelect v-model="goodsVisible" @confirm="onGoodsSelected"></FreeGoodsSelect>
          <br /><br />
        </el-dialog>

        <!-- 批次号搜索列表弹出对话框 -->
        <el-dialog v-model="batchVisible" width="60%" style="height: auto;" draggable :show-close="true">
          <BatchListSelect v-model="batchVisible" @confirm="onBatchSelected" :goodsName="currentRow.goodsId">
          </BatchListSelect>
          <br /><br />
        </el-dialog>
      </template>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, defineProps, onMounted, inject } from "vue";
import { useRouter } from 'vue-router'
import { formatDate } from "@/util";
import { ElMessage } from 'element-plus'
import WareHouse from '@/views/basic/WareHouse.vue'
import FreeGoodsSelect from "@/util/FreeGoodsSelect.vue";
import BatchListSelect from "../inbound/BatchListSelect.vue";
let router = useRouter();

let axios = inject("axios");
let warehouseVisible = ref(false);
let warehouseRef = ref();
watch(warehouseVisible, (newVisible) => {
  if (!newVisible) {
    if (warehouseRef.value && warehouseRef.value.selectedArray.length > 0) {
      console.log("currentRow", currentRow.value)
      console.log("selectedArray", warehouseRef.value.selectedArray[0])
      if (currentWarehouse.value == 'source') {
        currentRow.value.sourceWarehouseId = warehouseRef.value.selectedArray[0].id
        currentRow.value.sourceWarehouseName = warehouseRef.value.selectedArray[0].name
      } else if (currentWarehouse.value == 'target') {
        currentRow.value.targetWarehouseId = warehouseRef.value.selectedArray[0].id
        currentRow.value.targetWarehouseName = warehouseRef.value.selectedArray[0].name
      }
      //获取到仓库编码，存数据库用，仓库name仅用作展示
      //用完之后清空，避免污染其他地方数据
      warehouseRef.value.clearSelected();
    }
  }
});

// 商品搜索对话框展示
let goodsVisible = ref(false)
//当前选中行
let currentRow = ref(null), currentIndex = ref(null);
let showBatch = ref(false);
//这里的selected就是选中的商品列表，可以通过自行处理这些数据
const onGoodsSelected = (selected) => {
  if (selected.length > 0) {
    //当前行后面添加选中的的商品信息
    let arr = [];
    for (let i = 0; i < selected.length; i++) {
      if (selected[i].type == 1) {
        showBatch.value = true; //此处应该是每次数组变化，就需要进行判断，改成watch -------------------------------未改------------------------------
      }
      let obj = {
        goodsId: selected[i].id,
        goodsCode: selected[i].code,
        goodsName: selected[i].code + ' ' + selected[i].name,
        unitId: selected[i].unitId || null,
        unitName: selected[i].unitName || null,
        categoryId: selected[i].categoryId || null,
        categoryName: selected[i].categoryName || null,
        availableStock: selected[i].availableStock || null,
        specification: selected[i].specification || null,
        sourceWarehouseId: selected[i].warehouseId || null,
        sourceWarehouseName: selected[i].warehouseName || null,
        batchNo: selected[i].type == 1 ? selected[i].batchNo : null,
        birthday: selected[i].type == 1 ? selected[i].birthday : null,
        expiration: selected[i].type == 1 ? selected[i].expiration : null,
        type: selected[i].type || null,
        quantity: 1, //默认
        unitPrice: 0.0,
        totalPrice: 0.0,
      }
      arr[i] = obj
    }
    console.log("arr", arr);
    //当前下标往后添加选中的商品
    detailList.value.splice(currentIndex.value, 1, ...arr);
    console.log("onGoodsSelected", selected)
  }
}
// 商品搜索选择对话框
function openGoodsDialog(row, index) {
  goodsVisible.value = true;
  currentRow.value = row;
  currentIndex.value = index;
  console.log("当前选中行：", row)
}

let currentWarehouse = ref(null)
// 仓库搜索选择框
function openWarehouseDialog(row, tag) {
  currentWarehouse.value = tag;
  currentRow.value = row;
  warehouseVisible.value = true;
}


//这例的selected就是选中的批次列表
const onBatchSelected = (selected) => {
  if (selected.length > 0) {
    let arr = []
    for (let i = 0; i < selected.length; i++) {
      let obj = JSON.parse(JSON.stringify(currentRow.value)); //深拷贝
      obj.batchNo = selected[i].code;
      arr.push(obj);
    }
    //这里是参考精斗云中的效果，选中多个批次，则复制几份对象
    detailList.value.splice(currentIndex.value, 1, ...arr);
  }
}

let batchVisible = ref(false);
// 批次搜索选择框
function openBatchDialog(row, index) {
  batchVisible.value = true;
  currentRow.value = row;
  currentIndex.value = index;
  console.log("当前选中行：", row)
}
// 库位搜索选择框
// function openWarehouseLocationDialog(row) {
//   // if (!row.targetWarehouseId && ) { 不强制选择库位，可以在
//   //   ElMessage({ message: '请先选择仓库！', type: 'warning', })
//   //   return;
//   // }
//   row.warehouseLocationCode = "KW_TEST"
//   row.warehouseLocationName = "测试库位"
//   currentRow.value = row;
// }



const addDetailRow = (index) => {
  detailList.value.splice(index + 1, 0, {});
}
const removeDetailRow = (index) => {
  if (detailList.value.length === 1) {
    ElMessage({
      message: '至少保留一条记录',
      type: 'warning',
    })
    return;
  }
  detailList.value.splice(index, 1);
}

//如果接收到props(id，路由中加上了props:true)，则此组件为编辑明细、没有则为新增
const props = defineProps(["id"]);

const date = new Date()
//调拨单信息
const allotOrder = ref({
  code: '',
  createdTime: formatDate(date),
  remark: '',
  status: 1,
});
// 调拨单明细
const detailList = ref([
  {}
]);

// 新增前的校验
let filteredDetailList = ref(null);
const validSave = () => {
  // 过滤掉 goods 为空的明细项
  filteredDetailList.value = detailList.value.filter(item => {
    // 检查 goods 是否不为空
    return item.goodsId && item.goodsName;
  });
  //校验数据是否合理
  //1、校验调拨明细
  if (!filteredDetailList.value || filteredDetailList.value.length == 0) { ElMessage({ message: '请添加调拨明细', type: 'warning', }); return false; }
  for (let i = 0; i < filteredDetailList.value.length; i++) {
    let detail = filteredDetailList.value[i];
    if (!detail.sourceWarehouseId || !detail.targetWarehouseId) { ElMessage({ message: `请选择【${detail.goodsName}】的仓库`, type: 'warning', }); return false; }
    if (detail.quantity <= 0) { ElMessage({ message: `商品【${detail.goodsName}】的数量不能为空`, type: 'warning', }); return false; }
    if (detail.type && detail.type == 1 && !detail.batchNo) { ElMessage({ message: `商品【${detail.goodsName}】的批次号不能为空`, type: 'warning', }); return false; }
    // if (!detail.warehouseLocationCode || !detail.warehouseLocationName) { ElMessage({ message: `请选择【${detail.goodsName}】的库位`, type: 'warning', }); return false; }
    if (detail.sourceWarehouseId == detail.targetWarehouseId) { ElMessage({ message: '出库仓库和入库仓库不能相同！', type: 'warning' }); return false; }
  }
  return true;
}


const save = () => {
  if (props.id || allotOrder.value.id) { //修改操作
    console.log("修改");
    if (validSave()) {
      modify();
    }
  } else { // 新增操作
    console.log("新增");
    if (validSave()) { //校验通过
      add();
    }
  }
}

const saveAndSubmit = () => {
  allotOrder.value.status = 2;
  save();
}

const auditor = () => {

}

// 修改
let originalDetailList = ref(null), originalOrder = ref(null);
const modify = async () => {
  //1.map根据id快速获取原数组
  const originalMap = new Map(
    originalDetailList.value.map(item => [item.id, item])
  );
  //2.遍历当前列表：找新增 & 修改
  let addList = [], delList = [], modList = [];
  filteredDetailList.value.forEach(i => {
    if (!i.id) {
      addList.push(i); //新增
    } else {
      if (hasModifiedDetail(i, originalMap.get(i.id))) {
        modList.push(i);
      }
      //map数据比较过就删除， map中数据 - 当前明细 = 已删除数据
      originalMap.delete(i.id);
    }
  })
  //3.剩下的 originalMap 中的 id 就是被删除的
  for (const id of originalMap.keys()) {
    delList.push(id);
  }
  //提交修改
  try {
    const rs = await axios({
      url: `/xyy/allot/modify`,
      method: 'post',
      data: {
        orderModified: hasModifiedOrder(originalOrder.value, allotOrder.value),
        addList: addList,
        modList: modList,
        delList: delList,
        allot: allotOrder.value
      }
    })
    if (rs.data.code == 5200) {
      ElMessage({ message: "修改调拨单成功", type: 'success', });
      router.push({ name: 'allot' });
      return;
    }
    ElMessage({ message: "修改调拨单失败", type: 'danger', });
  } catch (error) {
    console.log(error);
    ElMessage({ message: `修改调拨单异常:${error.message}`, type: 'danger', });
  }

}
//判断当前 调拨明细 是否修改
function hasModifiedDetail(current, original) { //判断这个商品是否修改的前提：商品id或code存在，其他：商品单位、仓库、批次号、库位、数量、单价修改即表示该明细修改了
  const fields = ["unitId", "sourceWarehouseId", "targetWarehouseId", "batchId", "goodsId", "quantity"];
  return fields.some(field => current[field] != original[field]);
}
//判断当前 调拨单 是否修改
function hasModifiedOrder(current, original) {
  const fields = ["createdTime", "remark", "status"]
  return fields.some(field => current[field] != original[field]);
}

// 新增
const add = async () => {
  try {
    const rs = await axios({
      url: '/xyy/allot/create', method: 'post',
      data: {
        allot: allotOrder.value,
        detailList: filteredDetailList.value
      }
    })
    if (rs.data.code == 5200) {
      ElMessage({ message: '新增调拨单成功！', type: 'success' })
      router.push({ name: 'allot' });
      return;
    } else {
      ElMessage({ message: '新增调拨单失败！', type: 'danger' })
    }
  } catch (error) {
    ElMessage({ message: error.message, type: 'danger' })
  }
}


const init = async () => {
  try {
    const rs = await axios({
      url: `/xyy/allot/get/${props.id}`,
      method: 'post',
    })

    if (rs.data.code == 5200) {
      allotOrder.value = rs.data.allotRequest.allot;
      detailList.value = rs.data.allotRequest.detailList;

      detailList.value.forEach(i => {
        if (i.type == 1) {
          showBatch.value = true;
        }
      })
      //深拷贝一份初始数据，方便后面操作
      originalOrder.value = JSON.parse(JSON.stringify(rs.data.allotRequest.allot));
      originalDetailList.value = JSON.parse(JSON.stringify(rs.data.allotRequest.detailList));
      return;
    }
    ElMessage({ message: '', type: 'danger' })

  } catch (error) {
    console.log(error);
  }

}

onMounted(() => {
  if (props.id) {
    init();
  }
})

</script>

<style scoped>
.container :deep(.el-divider--horizontal) {
  margin: 10px 0;
}

.container :deep(.el-form-item) {
  margin: 0;
}

/* 调整当前组件内所有 inline form-item 的间距 */
:deep(.el-form--inline .el-form-item) {
  margin-right: 20px; /* 默认是 12px */
}
span {
  color: rgba(55, 54, 54, 0.674)
}
</style>